trigger trg_ChamberHistory on Chamber_History__c (after insert,before update)
{
    Map<ID,ID> chamberObjectIdMap = new Map<ID,ID>();

	if(Trigger.isUpdate)
	{
		for(Chamber_History__c chamberObject : Trigger.New)
	    {
	        if(chamberObject.Amendment__c != null)
	        {
	            if(chamberObject.Chamber_History_Status__c == 'Approved by Chamber')
	            {
	                if(Trigger.oldMap.get(chamberObject.Id).Chamber_History_Status__c != chamberObject.Chamber_History_Status__c)
	                {
	                	
	                	if(chamberObject.isChamberAmendmentConfirmed__c == 'false')
	                	{
		                    //WE only need to query the Amendment Object which is also selected on the Amendment Page Layout...    
		                    chamberObjectIdMap.put(chamberObject.Id, chamberObject.Company__c);
	                	}
	                }
	                
	            }
	        
	        }
	    
	    }	
	}
	else if (Trigger.isInsert)
	{
		for(Chamber_History__c chamberObject : Trigger.New)
	    {
	        if(chamberObject.Amendment__c != null)
	        {
	            if(chamberObject.Chamber_History_Status__c == 'Approved by Chamber')
	            {
	            	if(chamberObject.isChamberAmendmentConfirmed__c == 'false')
                	{
                		//WE only need to query the Amendment Object which is also selected on the Amendment Page Layout...    
                    	chamberObjectIdMap.put(chamberObject.Id, chamberObject.Company__c);	
                	}
                    
	            }
	        
	        }
	    
	    }
		
	}
	
    //Now The Business Logic Begins..
    if(chamberObjectIdMap.size() > 0)
    {
        //First Query to the Account Object...
        try
        {
        	Map<ID,Account> accountObjectMap = new Map<ID,Account>([SELECT id,Name, LegalStatus__c,Authorized_Manager__c,Activity__c,company_name_arabic__c,(Select Id,Company__c,Shareholder__r.Passport_Number_Formula__c,Shareholder__r.Gender__c,Shareholder__r.Arabic_Name__c, Shareholder__c, Ownership__c,Share_Profit__c From Share_Ownerships__r) ,(SELECT Account__c,Active__c,Activity__c FROM Account_Activities__r where Active__c =: true)  FROM Account where Id IN: chamberObjectIdMap.values()]);
	        Map<String,ID> legalStatusMap = new Map<String,ID>();
	        
	        
	        
	        if(accountObjectMap.size() > 0)
	        {    
	            for(Legal_Status__c legalStatus : [SELECT Id,Short_Name_English__c from Legal_Status__c where Short_Name_English__c =: 'F.Z.E' OR Short_Name_English__c =: 'F.Z.C'])
	            {
	                legalStatusMap.put(legalStatus.Short_Name_English__c,legalStatus.id);
	            
	            }
	            
	            
	            List<Account> accountObjectUpdateList = new List<Account>();
	            List<Account_Activity__c> accountActivityObjectUpdateList = new List<Account_Activity__c>();
	            List<Account_Activity__c> accountActivityObjectDeleteList = new List<Account_Activity__c>();
	            List<Account_Activity__c> accountActivityInsertList = new List<Account_Activity__c>();
	            
	            List<Share_Ownership__c> shareOwnershipDeleteList = new List<Share_Ownership__c>();
	            List<Share_Ownership__c> shareOwnershipInsertList = new List<Share_Ownership__c>();
	            List<Share_Ownership__c> shareOwnershipEditList = new List<Share_Ownership__c>();
	
	            //License Type...
	            List<Account_Activity__c> licenseAccountActivityDeleteList = new List<Account_Activity__c>();
	            List<Account_Activity__c> licenseAccountActivityInsertList = new List<Account_Activity__c>();
	            List<Account_Activity__c> licenseAccountActivityEditList = new List<Account_Activity__c>();
	            
	            for(Amendment__c amendmentObject : [select Total_Share_Holders__c,New_License_Type__c,Id,Total_Share_Ownership__c,New_Activity_1__c,Action__c,New_Authorize_Manager__c,New_Activity_2__c,New_Activity_3__c,Current_Activity_1__c,Current_Activity_2__c,Current_Activity_3__c, Record_Type_Name_Formula__c, Chamber_History__c, New_Company_Name__c,New_Company_Name_Arabic__c, Account__c,(SELECT id,name,Account__c,Active__c,Add_Flag__c,Edit_Flag__c,Delete_Flag__c,Activity_Arabic_Name__c,Activity_English_Name__c,Amendment__c,Account_Activity__c,Activity__c FROM Amendment_Activities__r),(SELECT Id,Add_Flag__c,Edit_Flag__c,Delete_Flag__c,NAME,Contact__r.Passport_Number_Formula__c,Account__c,Action__c,Contact__r.Arabic_Name__c,Contact__r.Gender__c,Contact__c,Ownership__c,Share_Profit__c,Share_Ownership__c,ShareHolder_Name__c FROM Shareholder_Amendments__r) FROM Amendment__c where Chamber_History__c IN: chamberObjectIdMap.keyset() ])
	            {
	                
	                if(amendmentObject.Record_Type_Name_Formula__c == 'Company_Amendment_Change_Company_Name')
	                {
	                    //Change the Account Name And Account Arabic Name...
	                    if(amendmentObject.Account__c == accountObjectMap.get(amendmentObject.Account__c).Id)
	                    {
	                        Account tempAccount = accountObjectMap.get(amendmentObject.Account__c);
	                        
	                        tempAccount.Name = amendmentObject.New_Company_Name__c;
	                        tempAccount.company_name_arabic__c = amendmentObject.New_Company_Name_Arabic__c;
	                        
	                        //Adding in the Account update list...
	                        accountObjectUpdateList.add(tempAccount);
	                       
	                    }
	                
	                }
	                else if(amendmentObject.Record_Type_Name_Formula__c == 'Company_Amendment_Change_License_Type')
	                {
	                    if(amendmentObject.Account__c == accountObjectMap.get(amendmentObject.Account__c).Id)
	                    {
	                    	Account tempAccount = accountObjectMap.get(amendmentObject.Account__c);
	                        
	                        tempAccount.Activity__c = amendmentObject.New_License_Type__c;
	                        
	                    	//Adding in the Account update list...
	                        accountObjectUpdateList.add(tempAccount);
	                    	
	                        //For Amendment Activity...
	                        for(Amendment_Activity__c amendmentActivityObject : amendmentObject.Amendment_Activities__r)
	                        {
	                            System.debug('The Amendemnt Activity => '+ amendmentActivityObject.name + ' && The Amendment Add Flag => ' + amendmentActivityObject.Add_Flag__c + ' && The Edit Flag => '+ amendmentActivityObject.Edit_Flag__c + ' && The Delete Flag => '+ amendmentActivityObject.Delete_Flag__c );
	                            if(amendmentActivityObject.Add_Flag__c == true)
	                            {
	                                 System.debug('Comes Under the Add Flag...');
	                                 if(amendmentActivityObject.Account_Activity__c == null)
	                                 {
	                                     Account_Activity__c tempAccountActivityObject = new Account_Activity__c();
	                                     tempAccountActivityObject.Account__c = accountObjectMap.get(amendmentObject.Account__c).Id;
	                                     tempAccountActivityObject.Active__c = amendmentActivityObject.Active__c;
	                                     tempAccountActivityObject.Activity__c = amendmentActivityObject.Activity__c;
	                                     
	                                     //Adding in the List...
	                                     licenseAccountActivityInsertList.add(tempAccountActivityObject);
	                                 
	                                 }
	                                        
	                            }
	                            else if(amendmentActivityObject.Edit_Flag__c == true || amendmentActivityObject.Delete_Flag__c == true)  
	                            {
	                                for(Account_Activity__c accountActivityObject : accountObjectMap.get(amendmentObject.Account__c).Account_Activities__r)
	                                {
	                                    System.debug('The Share Amendment Name => '+ amendmentActivityObject.name + ' && The Delete Flag => '+ amendmentActivityObject.Delete_Flag__c);
	                                    if(amendmentActivityObject.Account_Activity__c == accountActivityObject .Id)
	                                    {
	                                        //if(shareAmendmentObject.Action__c == 'Remove')
	                                        if(amendmentActivityObject.Delete_Flag__c == true)
	                                        {
	                                           System.debug('The Delete Flag in Share Amendment => ' + amendmentActivityObject.Delete_Flag__c );
	                                           accountActivityObject.Active__c = false;
	                                           licenseAccountActivityDeleteList.add(accountActivityObject );
	                                        }
	                                        //else if(shareAmendmentObject.Action__c == 'Edit' || shareAmendmentObject.Action__c == 'Replace')
	                                        else if(amendmentActivityObject.Edit_Flag__c == true)
	                                        {
	                                            System.debug('In the Edit Flag List...');
	                                            accountActivityObject.Active__c= amendmentActivityObject.Active__c;
	                                            accountActivityObject.Activity__c = amendmentActivityObject.Activity__c;
	                                            
	                                            //Adding in the Updation list...
	                                            licenseAccountActivityEditList.add(accountActivityObject);
	                                            
	                                        }
	                                        
	                                        //Break the Loop...
	                                        break;
	                                    }
	                                
	                                }
	                            
	                            }    
	                        
	                        }
	                    
	                    
	                    }
	                
	                
	                }
	                else if(amendmentObject.Record_Type_Name_Formula__c == 'Shareholder_Amendment_Add_Partner' || amendmentObject.Record_Type_Name_Formula__c == 'Shareholder_Amendment_Replace_Partner' || amendmentObject.Record_Type_Name_Formula__c == 'Shareholder_Amendment_Remove_Partner')
	                {
	                    
	                    
	                    if(amendmentObject.Account__c == accountObjectMap.get(amendmentObject.Account__c).Id)
	                    {
	                        if(amendmentObject.Total_Share_Holders__c > 1)
	                        {
	                            accountObjectMap.get(amendmentObject.Account__c).LegalStatus__c =  legalStatusMap.get('F.Z.C');           
	                            //Adding in the Account update list...
	                            accountObjectUpdateList.add(accountObjectMap.get(amendmentObject.Account__c));
	                        }
	                        else
	                        {
	                            accountObjectMap.get(amendmentObject.Account__c).LegalStatus__c =  legalStatusMap.get('F.Z.E'); 
	                            //Adding in the Account update list...
	                            accountObjectUpdateList.add(accountObjectMap.get(amendmentObject.Account__c));
	                        }
	                            
	                        //For Share HOlder...
	                        for(Shareholder_Amendment__c shareAmendmentObject : amendmentObject.Shareholder_Amendments__r)
	                        {
	                            System.debug('AboveThe Share Amendment Name => '+ shareAmendmentObject.name + ' && The Delete Flag => '+ shareAmendmentObject.Delete_Flag__c);
	                                    
	                            //if(shareAmendmentObject.Action__c == 'Add')
	                            if(shareAmendmentObject.Add_Flag__c == true)
	                            {
	                                 if(shareAmendmentObject.Share_Ownership__c == null)
	                                 {
	                                     System.debug('Under the Share Ownershipt => '+ shareAmendmentObject.Share_Ownership__c);
	                                     Share_Ownership__c tempShareOwnerObject = new Share_Ownership__c();
	                                     tempShareOwnerObject.Company__c = accountObjectMap.get(amendmentObject.Account__c).Id;
	                                     tempShareOwnerObject.Ownership__c = shareAmendmentObject.Ownership__c;
	                                     tempShareOwnerObject.Share_Profit__c = shareAmendmentObject.Share_Profit__c;
	                                     tempShareOwnerObject.Shareholder__c = shareAmendmentObject.Contact__c;    
	                                     
	                                     //Adding in the List...
	                                     shareOwnershipInsertList.add(tempShareOwnerObject);
	                                 
	                                 }
	                                        
	                            }
	                            //else if(shareAmendmentObject.Action__c == 'Edit' || shareAmendmentObject.Action__c == 'Replace' || shareAmendmentObject.Action__c == 'Remove')  
	                            else if(shareAmendmentObject.Edit_Flag__c == true || shareAmendmentObject.Delete_Flag__c == true)  
	                            {
	                                for(Share_Ownership__c shareOwnershipObject : accountObjectMap.get(amendmentObject.Account__c).Share_Ownerships__r)
	                                {
	                                    System.debug('The Share Amendment Name => '+ shareAmendmentObject.name + ' && The Delete Flag => '+ shareAmendmentObject.Delete_Flag__c);
	                                    if(shareAmendmentObject.Share_Ownership__c == shareOwnershipObject.Id)
	                                    {
	                                        //if(shareAmendmentObject.Action__c == 'Remove')
	                                        if(shareAmendmentObject.Delete_Flag__c == true)
	                                        {
	                                           System.debug('The Delete Flag in Share Amendment => ' + shareAmendmentObject.Delete_Flag__c );
	                                           shareOwnershipDeleteList.add(shareOwnershipObject);
	                                        }
	                                        //else if(shareAmendmentObject.Action__c == 'Edit' || shareAmendmentObject.Action__c == 'Replace')
	                                        else if(shareAmendmentObject.Edit_Flag__c == true)
	                                        {
	                                            shareOwnershipObject.Ownership__c = shareAmendmentObject.Ownership__c;
	                                            shareOwnershipObject.Share_Profit__c = shareAmendmentObject.Share_Profit__c;
	                                            shareOwnershipObject.Shareholder__c = shareAmendmentObject.Contact__c;
	                                            
	                                            //Adding in the List...
	                                            shareOwnershipEditList.add(shareOwnershipObject);
	                                        }
	                                        
	                                        //Break the Loop...
	                                        break;
	                                    }
	                                
	                                }
	                            
	                            }
	                            
	                        
	                        }
	                    }
	                
	                
	                }
	                else if(amendmentObject.Record_Type_Name_Formula__c == 'Company_Amendment_Change_Company_Manager') 
	                {
	                    //Change the Account Name And Account Arabic Name...
	                    if(amendmentObject.Account__c == accountObjectMap.get(amendmentObject.Account__c).Id)
	                    {
	                        Account tempAccount = accountObjectMap.get(amendmentObject.Account__c);
	                        tempAccount.Authorized_Manager__c = amendmentObject.New_Authorize_Manager__c;
	                        //Adding in the Account update list...
	                        accountObjectUpdateList.add(tempAccount);
	                        
	                    }    
	                
	                }
	                else if(amendmentObject.Record_Type_Name_Formula__c == 'Company_Amendment_Change_Company_Activity')
	                {
	                    //Check the Amendment Associated to the Account...
	                    if(amendmentObject.Account__c == accountObjectMap.get(amendmentObject.Account__c).Id)
	                    {
	                        if(amendmentObject.Action__c == 'Edit' || amendmentObject.Action__c == 'Delete')
	                        {
	                            for(Account_Activity__c accountActivityObject : accountObjectMap.get(amendmentObject.Account__c).Account_Activities__r)
	                            {
	                                if(amendmentObject.Action__c == 'Edit')
	                                {
	                                    if(accountActivityObject.Activity__c == amendmentObject.Current_Activity_1__c)
	                                    {
	                                        if(amendmentObject.New_Activity_1__c != null)
	                                            accountActivityObject.Activity__c = amendmentObject.New_Activity_1__c;
	                                    }
	                                    else if(accountActivityObject.Activity__c == amendmentObject.Current_Activity_2__c)
	                                    {
	                                        if(amendmentObject.New_Activity_2__c != null)
	                                            accountActivityObject.Activity__c = amendmentObject.New_Activity_2__c;
	                                    }
	                                    else if(accountActivityObject.Activity__c == amendmentObject.Current_Activity_3__c)
	                                    {
	                                        if(amendmentObject.New_Activity_3__c != null)
	                                            accountActivityObject.Activity__c = amendmentObject.New_Activity_3__c;
	                                    }
	                                    
	                                    //Now Add the Account Activity to Update the list...
	                                    accountActivityObjectUpdateList.add(accountActivityObject);
	                                }
	                                else if(amendmentObject.Action__c == 'Delete')
	                                {
	                                    if(accountActivityObject.Activity__c == amendmentObject.Current_Activity_1__c)
	                                    {
	                                    	accountActivityObject.Active__c = false;
	                                        accountActivityObjectDeleteList.add(accountActivityObject);    
	                                    }
	                                    else if(accountActivityObject.Activity__c == amendmentObject.Current_Activity_2__c)
	                                    {
	                                        accountActivityObject.Active__c = false;
	                                        accountActivityObjectDeleteList.add(accountActivityObject);     
	                                    }
	                                    else if(accountActivityObject.Activity__c == amendmentObject.Current_Activity_3__c)
	                                    {
	                                    	accountActivityObject.Active__c = false;
	                                        accountActivityObjectDeleteList.add(accountActivityObject); 
	                                    }
	                                
	                                }
	                                
	                            }
	
	                        
	                        }
	                        else if(amendmentObject.Action__c == 'Add')
	                        {
	                            if(amendmentObject.New_Activity_1__c != null)
	                            {
	                                Account_Activity__c acountActivityObject = new Account_Activity__c();
	                                acountActivityObject.Account__c = amendmentObject.Account__c;
	                                acountActivityObject.Activity__c = amendmentObject.New_Activity_1__c;
	                                acountActivityObject.Active__c = true;
	                                
	                                System.debug('The Account Activity => '+ acountActivityObject.Active__c);
	                                //Now Adding in the list...
	                                accountActivityInsertList.add(acountActivityObject);
	                            }
	                            if(amendmentObject.New_Activity_2__c != null)
	                            {
	                                Account_Activity__c acountActivityObject = new Account_Activity__c();
	                                acountActivityObject.Account__c = amendmentObject.Account__c;
	                                acountActivityObject.Activity__c = amendmentObject.New_Activity_2__c;
	                                acountActivityObject.Active__c = true;
	                                
	                                //Now Adding in the list...
	                                accountActivityInsertList.add(acountActivityObject);
	                            }
	                            if(amendmentObject.New_Activity_3__c != null)
	                            {
	                                Account_Activity__c acountActivityObject = new Account_Activity__c();
	                                acountActivityObject.Account__c = amendmentObject.Account__c;
	                                acountActivityObject.Activity__c = amendmentObject.New_Activity_3__c;
	                                acountActivityObject.Active__c = true;
	                                
	                                //Now Adding in the list...
	                                accountActivityInsertList.add(acountActivityObject);
	                            }
	                            
	                        
	                        }
	                                                
	                    }
	                
	                }
	                 
	            
	            }
	            
	            
	            //Now Update the Account Object...
	            if(accountObjectUpdateList.size() > 0)
	                update accountObjectUpdateList ;
	            
	            //Now Update the Account Activity Object...
	            if(accountActivityObjectUpdateList.size() > 0)
	                update accountActivityObjectUpdateList;
	            //Now Delete the Account Activity Object...
	            if(accountActivityObjectDeleteList.size() > 0)
	            {
	                //delete accountActivityObjectDeleteList;
	                update accountActivityObjectDeleteList;
	            }
	            
	            System.debug('The Account Activity Insert List => '+ accountActivityInsertList.size());
	            //Now Insert the Account Activity Object...  
	            if(accountActivityInsertList.size() > 0 )
	                insert accountActivityInsertList;  
	        
	            //For Share Ownershipp....
	            if(shareOwnershipInsertList.size() > 0)
	               insert shareOwnershipInsertList;
	            if(shareOwnershipEditList.size() > 0)
	               update shareOwnershipEditList;
	            System.debug('The Delete List => '+ shareOwnershipDeleteList.size());   
	            if(shareOwnershipDeleteList.size() > 0)
	               delete shareOwnershipDeleteList;     
	                       
	            //For License Type....
	            System.debug('The Delete List => '+ licenseAccountActivityDeleteList.size());   
	            if(licenseAccountActivityDeleteList.size() > 0)
	            {
	             	update licenseAccountActivityDeleteList;
	               //delete licenseAccountActivityDeleteList;        
	            }
	            System.debug('The Edit List => '+ licenseAccountActivityEditList.size());      
	            if(licenseAccountActivityEditList.size() > 0)
	               update licenseAccountActivityEditList;
	            System.debug('The Insert List => '+ licenseAccountActivityInsertList.size());   
	            if(licenseAccountActivityInsertList.size() > 0)
	               insert licenseAccountActivityInsertList;
	            
	            
	        
	        }
        	
        }
        catch(Exception exp)
        {
        	System.debug('The Exception => '+ exp.getMessage());
        	//throw exp;
        	for(Chamber_History__c chamberObject : Trigger.New)
        	{
        		chamberObject.addError(exp.getMessage());
        		break;
        	}
        	
        	
        	
        }
        
            
    }
    



}